from typing import List, Any
from enum import Enum, auto, unique

from django.core.handlers.wsgi import WSGIRequest
from django.core.paginator import Paginator, InvalidPage, Page
from django.db.models import QuerySet
from rest_framework.serializers import ModelSerializer

from jqexception.jqexecption import ValueErr


class JQPagination:
    """
    分页操作封装类
    """

    @unique
    class QueryParam(Enum):
        page = auto()
        page_size = auto()

    def __init__(self, serializer: ModelSerializer):
        self._ser: ModelSerializer = serializer
        # 默认每页大小
        self._paginator: Paginator = None

    def _get_page_number(self, request: WSGIRequest):
        r = request.GET.get(self.QueryParam.page.name, 1)
        return int(r)

    def _get_page_size(self, request: WSGIRequest):
        r = request.GET.get(self.QueryParam.page_size.name, 20)
        return int(r)

    def paginate(self, queryset: QuerySet, request: WSGIRequest) -> dict:
        page_size = self._get_page_size(request)
        page_number = self._get_page_number(request)

        self._paginator = Paginator(queryset, page_size)
        page = self._paginator.page(page_number)
        json_list = self._ser(page.object_list, many=True).data
        r = {
            "sum_count": self._paginator.count,
            "list": json_list,
        }
        return r
